package com.cookbook.cookbookservice.service.impl;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.cookbook.cookbookservice.mapper.UserMapper;
import com.cookbook.cookbookservice.model.User;
import com.cookbook.cookbookservice.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    TimedCache<String, String> timedCache = CacheUtil.newTimedCache(4);

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 登录
     *
     * @param unionid 微信id
     * @param token   微信token
     * @param timeout 微信返回的过期时间
     * @return
     */
    @Override
    public User login(String unionid, String token, long timeout) {
        try {
            // 查询是否已经存在该用户
            User user = userMapper.getUser(unionid);
            if (user == null) {
                // 不存在进行保存
                user = new User();
                user.setUnionid(unionid);
                // 随机选取一个头像
                user.setUserHead("");
                // 随机生成昵称
                user.setUserName(getRandomJianHan(6));
                // 保存用户
                userMapper.insertUser(user);
            }
            // 缓存中保存此token
            timedCache.put(token, unionid, timeout);
            // 返回
            return user;
        } catch (Exception e) {
            logger.error("登录失败", e);
            return null;
        }

    }

    /**
     * 通过token获取用户
     *
     * @param token
     * @return
     */
    @Override
    public User getUser(String token) {
        String unionid = timedCache.get(token);
        if (StringUtils.isBlank(unionid)) {
            return null;
        }
        User user = userMapper.getUser(unionid);
        return user;
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return
     */
    @Override
    public User updateUser(User user) {
        try {
            userMapper.updateUser(user);
            return userMapper.getUser(user.getUnionid());
        } catch (Exception e) {
            logger.error("修改用户失败", e);
            return null;
        }

    }


    private String getRandomJianHan(int len) {
        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < len; i++) {
            String str = null;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBK"); // 转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret.append(str);
        }
        return ret.toString();
    }
}
